<!-- 人员技能 -->
<template>
  <basic-container>
    <avue-crud
      :option="option"
      :table-loading="loading"
      :data="data"
      :defaults.sync="defaults"
      :page.sync="page"
      :before-open="beforeOpen"
      v-model="form"
      ref="crud"
      @search-change="searchChange"
      @search-reset="searchReset"
      @selection-change="selectionChange"
      @current-change="currentChange"
      @size-change="sizeChange"
      @refresh-change="refreshChange"
      @on-load="onLoad"
    >
      <template slot="menuLeft">
        <el-button type="primary" size="small" icon="el-icon-plus" v-if="permission.person_skills_add" @click="handleAdd">新 增 </el-button>
        <el-button type="success" size="small" v-if="permission.person_skills_batch_config" @click="handleBatchConfig">批量配置人员技能</el-button>
        <el-button type="success" size="small" icon="el-icon-upload2" v-if="permission.person_skills_import" @click="importModalVisiable = true">导 入</el-button>
        <el-button type="warning" size="small" plain icon="el-icon-download" v-if="permission.person_skills_export" @click="$refs.exportComp.visible = true">导 出</el-button>
      </template>
      <template slot="menuRight">
        <user-table-config :option="option" @confirm="(val) => handleSetUserConfig(val, pageCode)"></user-table-config>
      </template>
      <template slot="menu" slot-scope="{ row }">
        <el-button type="text" size="small" icon="el-icon-view" v-if="permission.person_skills_view" @click="handleView(row)">详情</el-button>
        <el-button type="text" size="small" icon="el-icon-edit" v-if="permission.person_skills_edit" @click="handleEdit(row)">编辑</el-button>
        <el-button type="text" size="small" icon="el-icon-delete" v-if="permission.person_skills_delete" @click="handleDelete(row)">删除</el-button>
      </template>
    </avue-crud>

    <importDialogComp
      title="人员技能导入"
      url="/api/mes-admin/userskill/import"
      export-name="人员技能导入模板.xlsx"
      :form-data="fromData"
      :is-form-data-json="true"
      :visible.sync="importModalVisiable"
      :config-columns="['dataRepeat']"
      :params="{}"
      @submit="codeClose"
    ></importDialogComp>
    <export-comp ref="exportComp" page-api-url="mes-admin/userskill/list" :option="exportOption" :page="page" :query="query" file-name="人员技能"></export-comp>

    <!-- 技能配置/批量配置/展示弹窗 -->
    <el-dialog :title.sync="crudModalTitle" append-to-body class="crud-modal person-skills-modal" :visible.sync="crudModalVisiable" @close="handleCrudModalClose" top="5vh">
      <template>
        <vertical-bar-title>人员信息</vertical-bar-title>
        <avue-form v-if="crudModalState != 'batchConfig'" ref="personInfoForm" v-model="personInfoForm" :option="personInfoFormOption"></avue-form>
      </template>
      <avue-crud v-if="crudModalState == 'batchConfig'" :option="personInfoCrudOption" :data="batchConfigPersonInfoData" @row-del="personInfoRowDel">
        <template slot="menuLeft">
          <el-button type="primary" size="small" icon="el-icon-plus" @click="openUserListModal('batchConfigUserList')">新增人员</el-button>
        </template>
      </avue-crud>
      <template>
        <vertical-bar-title>配置技能</vertical-bar-title>
        <avue-crud
          :option="configSkillFormCrudOption"
          :data="crudSkillData"
          @row-del="configSkillFormRowDel"
          v-model="skillForm"
          :before-open="handleSkillFormBeforeOpen"
          :before-close="handleSkillFormBeforeClose"
        >
          <template slot="menuLeft">
            <el-button type="primary" size="small" icon="el-icon-plus" v-if="crudModalState != 'view'" @click="handleAddSkills">添加技能</el-button>
          </template>
          <!-- 技能证书 -->
          <template slot="attachJsonForm">
            <el-upload
              ref="skillAttachment"
              disabled
              class="importConfigDialog"
              drag
              action="/api/blade-resource/oss/endpoint/put-file-attach"
              :headers="headersObj"
              accept=".png,.gif,.bmp,.jpg,.jpeg,.doc,.docx,.xlsx,.xls,.pdf"
              :before-upload="handleBeforeUpload"
              :on-remove="removeFile"
              :on-success="handleUploadSuccess"
              :on-preview="handlePreview"
              :file-list="fileList"
            >
              <i class="el-icon-upload"></i>
              <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
            </el-upload>
          </template>
          <template slot-scope="{ row }" slot="status">
            <el-switch :disabled="crudModalState == 'view'" v-model="row.status" active-value="1" inactive-value="0" active-text="开" inactive-text="关"> </el-switch>
          </template>
        </avue-crud>
      </template>
      <template v-if="crudModalState == 'view'">
        <div class="groups">
          <div class="titleIcon">
            <i class="el-icon-vertical-bar avue-group__icon"></i>
            <h4>操作记录</h4>
          </div>
        </div>
        <avue-crud :option="operationRecordCrudOption" :data="operationRecordData"></avue-crud>
      </template>
      <span slot="footer" class="dialog-footer" v-if="crudModalState != 'view'">
        <el-button size="small" @click="handleCrudModalClose"><i class="el-icon-circle-close"></i><span>取 消</span></el-button>
        <el-button type="primary" size="small" @click="handleSavePersonSkillsConfigs"><i class="el-icon-circle-plus-outline"></i><span>提 交</span></el-button>
      </span>
    </el-dialog>

    <!-- 新增人员技能弹框 -->
    <el-dialog title="新增人员技能" append-to-body :visible.sync="addSkillsModalVisible" @close="handleAddSkillsModalClose" top="5vh">
      <div class="groups">
        <div class="titleIcon">
          <i class="el-icon-vertical-bar avue-group__icon"></i>
          <h4>技能信息</h4>
        </div>
      </div>
      <avue-form ref="personSkillForm" v-model="personSkillForm" :option="configSkillFormCrudOption">
        <template slot="attachJson">
          <el-upload
            ref="skillAttachment"
            class="importConfigDialog"
            drag
            action="/api/blade-resource/oss/endpoint/put-file-attach"
            :headers="headersObj"
            accept=".png,.gif,.bmp,.jpg,.jpeg,.doc,.docx,.xlsx,.xls,.pdf"
            :before-upload="handleBeforeUpload"
            :on-remove="removeFile"
            :on-success="handleUploadSuccess"
            :on-preview="handlePreview"
            :file-list="fileList"
          >
            <i class="el-icon-upload"></i>
            <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
          </el-upload>
        </template>
      </avue-form>
      <span slot="footer" class="dialog-footer">
        <el-button size="small" icon="el-icon-circle-close" @click="handleAddSkillsModalClose">取 消</el-button>
        <el-button size="small" type="primary" icon="el-icon-circle-plus-outline" @click="handleAddSkillsComfirm">提 交</el-button>
      </span>
    </el-dialog>
    <batch-person-config-modal
      :visible="batchPersonConfigVisible"
      :onClose="handleBatchPersonConfigModalClose"
      @on-submit="handleBatchPersonConfigModalSubmit"
    ></batch-person-config-modal>

    <!-- 公用模态框 此处用在了人员配置和技能选择 -->
    <common-modal-template ref="commonModalTemplate" :option="tableOption" @getSelectedRows="getSelectedRows"></common-modal-template>
  </basic-container>
</template>

<script>
import { mapGetters } from 'vuex';
import { getList, getDetail, add, update, remove, getOperationLog } from '@/api/product/person-skills';
import userConfig from '@/mixins/userConfig';
import userTableConfig from '@/components/user-table-config';
import importDialogComp from '@/components/dialog/import';
import exportComp from '@/components/export-comp';
import CommonModalTemplate from '@/components/common-modal-template/common-modal-template.vue';
import { crudOptionHelper, crudInModalOptionHelper, inputOptionHelper, selectOptionHepler, switchOptionHelper, textareaOptionHelper } from '../skill-list/skillsHelperFunction';
import { getToken } from '@/util/auth';
import { Base64 } from 'js-base64';
import website from '@/config/website';

import VerticalBarTitle from './VerticalBarTitle.vue';
import BatchPersonConfigModal from './BatchPersonConfigModal.vue';

const PAGE_NAME = 'person_skills';
// 接口字段
const FIELD = {
  // 人员信息
  USER_ID: 'userId', // 用户ID
  USER_NAME: 'userName', // 用户名称
  USER_CODE: 'userCode', // 用户编码
  ACCOUNT_NAME: 'userAccount', // 账号名
  DEPARTMENT: 'userDept', // 所属部门
  UPDATE_TIME: 'updateTime', // 更新时间
  UPDATE_PERSON: 'updateUser', // 更新人
  STATUS: 'status', // 状态
  REMAKR: 'remark', // 备注
  // 技能信息
  SKILL_ID: 'skillId',
  SKILL_NAME: 'skillName', //技能名称
  SKILL_CODE: 'skillCode', // 技能编码
  SKILL_TYPE: 'skillType', // 技能类型
  SKILL_LEVEL: 'skillLevel', // 技能等级
  VALIDAITY_START: 'skillValidPeriodStart', // 有效期
  VALIDAITY_END: 'skillValidPeriodEnd', // 有效期
  warning: 'skillExpirationAlertTime', // 技能到期预警时间（天）
  ATTACHMENT: 'attachJson', // 技能证件
  // 操作记录
  OPERAROR: 'createBy',
  OPERATION_TIME: 'createTime',
  OPERATION: 'remark' //操作内容
};

// 此部分字段对应于用户管理blade-system/user/page的字段
const USER_FIELD = {
  // 人员信息
  USER_ID: 'id', // 用户ID
  USER_NAME: 'realName', // 用户名称
  USER_CODE: 'code', // 用户编码
  ACCOUNT_NAME: 'account', // 账号名
  DEPARTMENT: 'deptName' // 所属部门
};

// 此部分字段对应于技能列表skill/page的字段
const SKILL_FIELD = {
  // 技能信息
  SKILL_ID: 'id',
  SKILL_NAME: 'name', //技能名称
  SKILL_CODE: 'code', // 技能编码
  SKILL_LEVEL: 'level', // 技能等级
  SKILL_TYPE: 'type', // 技能类型
  VALIDAITY: 'isValidPeriod', // 有效期
  warning: 'warning', // 技能到期预警时间（天）
  ATTACHMENT: 'attachJson' // 技能证件
};

const API_URLS = {
  PERSON_CONFIG: '/api/blade-system/page',
  SKILL_LIST: '/api/mes-admin/skill/page',
  SKILL_TYPE: '/api/blade-system/dict/dictionary?code=skill_type',
  SKILL_LEVEL: '/api/blade-system/dict/dictionary?code=skill_level'
};

export default {
  name: PAGE_NAME,
  mixins: [userConfig()],
  components: {
    userTableConfig,
    CommonModalTemplate,
    importDialogComp,
    exportComp,
    VerticalBarTitle,
    BatchPersonConfigModal
  },
  watch: {
    crudModalState(val, oldVal) {
      if (val == 'view') {
        this.configSkillFormCrudOption.delBtn = false;
      } else {
        this.configSkillFormCrudOption.delBtn = true;
      }
    },
    isGKJNYXQ(val, oldVal) {
      this.configSkillFormCrudOption.column[4].display = val;
      this.configSkillFormCrudOption.column[5].display = val;
    }
  },
  computed: {
    ...mapGetters(['permission']),
    ids() {
      let ids = [];
      this.selectionList.forEach((ele) => {
        ids.push(ele.id);
      });
      return ids.join(',');
    },
    headersObj() {
      let header = { Authorization: `Basic ${Base64.encode(`${website.clientId}:${website.clientSecret}`)}` };
      header['Blade-Auth'] = 'bearer ' + getToken();
      return header;
    },
    crudModalTitle() {
      switch (this.crudModalState) {
        case 'add':
          return '新增';
        case 'edit':
          return '编辑';
        case 'view':
          return '详情';
        case 'batchConfig':
          return '批量配置人员技能';
        default:
          return '';
      }
    }
  },
  data() {
    return {
      isView: false,
      isGKJNYXQ: false, // 管控技能有效期
      fileList: [],
      pageCode: PAGE_NAME,
      timer: new Date().getTime(), //不同内容使用同一个模态框结构，key值不同需要重新请求渲染数据，否则会请求到上一个使用的数据内容
      modalName: '', //打开公用模态框名称
      tableOption: {}, //公用模态框配置信息
      form: {},
      skillForm: {},
      defaults: {},
      query: {},
      loading: true,
      page: {
        pageSize: 20,
        currentPage: 1,
        total: 0
      },
      batchPersonConfigVisible: false,
      selectionList: [],
      option: crudOptionHelper({
        // 需要自定义新增/编辑/详情弹窗
        addBtn: false,
        editBtn: false,
        viewBtn: false,
        delBtn: false,
        viewTitle: '详情',
        column: [
          inputOptionHelper({ label: '用户名称', prop: FIELD.USER_NAME }),
          inputOptionHelper({ label: '用户编码', prop: FIELD.USER_CODE }),
          {
            label: '账号名',
            prop: FIELD.ACCOUNT_NAME,
            searchType: 'input'
          },
          {
            label: '所属部门',
            prop: FIELD.DEPARTMENT,
            editDisplay: false,
            addDisplay: false
          },
          {
            label: '更新人',
            prop: FIELD.UPDATE_PERSON,
            type: 'search'
          },
          {
            label: '更新时间',
            prop: FIELD.UPDATE_TIME
          }
        ]
      }),
      // 导出与显示不一致
      exportOption: crudOptionHelper({
        // 需要自定义新增/编辑/详情弹窗
        addBtn: false,
        editBtn: false,
        viewBtn: false,
        delBtn: false,
        viewTitle: '详情',
        column: [
          inputOptionHelper({ label: '用户名称', prop: FIELD.USER_NAME }),
          inputOptionHelper({ label: '用户编码', prop: FIELD.USER_CODE }),
          { label: '账号名', prop: FIELD.ACCOUNT_NAME, searchType: 'input' },
          { label: '所属部门', prop: FIELD.DEPARTMENT, editDisplay: false, addDisplay: false },
          selectOptionHepler({ label: '技能类型', prop: FIELD.SKILL_TYPE, dicUrl: API_URLS.SKILL_TYPE, search: false, disabled: true }),
          { label: '技能名称', prop: FIELD.SKILL_NAME },
          { label: '技能编码', prop: FIELD.SKILL_CODE },
          { label: '技能等级', type: 'select', prop: SKILL_FIELD.SKILL_LEVEL, dicUrl: API_URLS.SKILL_LEVEL, props: { label: 'dictValue', value: 'dictKey' } },
          { label: '技能有效期', prop: FIELD.VALIDAITY_START },
          { label: '技能到期预警时间（天）', prop: FIELD.warning },
          { label: '状态', prop: FIELD.STATUS },
          { label: '备注', prop: FIELD.REMAKR }
        ]
      }),
      data: [],

      fromData: {},
      // 弹框显示隐藏
      crudModalVisiable: false,
      crudModalState: '',
      addSkillsModalVisible: false,
      importModalVisiable: false,
      exportModalVisible: false,
      personInfoForm: {},
      personSkillForm: {},
      // 新增/编辑/详情-人员信息
      personInfoFormOption: {
        submitBtn: false,
        emptyBtn: false,
        detail: false,
        column: [
          {
            label: '用户名称',
            prop: FIELD.USER_NAME,
            search: true,
            disabled: true,
            type: 'search',
            order: 3,
            placeholder: '请选择 用户名称',
            rules: [
              {
                required: true,
                message: '请输入用户名称ID'
              }
            ],
            appendClick: () => {
              this.openUserListModal();
            }
          },
          {
            label: '用户编码',
            prop: FIELD.USER_CODE,
            disabled: true
          },
          {
            label: '所属部门',
            prop: FIELD.DEPARTMENT,
            disabled: true
          },
          {
            label: '账号名',
            prop: FIELD.ACCOUNT_NAME,
            disabled: true
          }
        ]
      },
      // 技能数据
      crudSkillData: [],
      // 操作记录数据
      operationRecordData: [],
      // 新增/编辑/详情-配置技能 + 批量配置人员-配置技能
      configSkillFormCrudOption: crudInModalOptionHelper({
        submitBtn: false,
        emptyBtn: false,
        addBtn: false,
        // addBtnText: '添加技能',
        menuWidth: 140,
        column: [
          {
            label: '技能名称',
            prop: FIELD.SKILL_NAME,
            type: 'search',
            search: false,
            disabled: true,
            appendClick: () => {
              this.openSkillListModal();
            },
            rules: [
              {
                required: true,
                message: `请选择技能名称`,
                trigger: 'blur'
              }
            ]
          },
          selectOptionHepler({ label: '技能类型', prop: FIELD.SKILL_TYPE, dicUrl: API_URLS.SKILL_TYPE, search: false, disabled: true }),
          inputOptionHelper({ label: '技能编码', prop: FIELD.SKILL_CODE, search: false, disabled: true }),
          selectOptionHepler({
            label: '技能等级',
            prop: FIELD.SKILL_LEVEL,
            dicUrl: API_URLS.SKILL_LEVEL,
            search: false,
            disabled: true,
            required: false
          }),
          {
            label: '技能有效期',
            labelWidth: 110,
            width: 255,
            prop: '_validaity',
            type: 'daterange',
            search: false,
            display: false,
            rules: [{ required: true, message: '请输入技能有效期' }],
            formatter: (row, value) => {
              if (row[FIELD.VALIDAITY_START]) {
                return row[FIELD.VALIDAITY_START].split('T')[0] + '至' + row[FIELD.VALIDAITY_END].split('T')[0];
              } else {
                return '';
              }
            }
          },
          {
            label: '技能到期预警时间（天）',
            prop: FIELD.warning,
            type: 'number',
            step: 1,
            // stepStrictly: true,
            // precision: 0,
            rules: [{ pattern: /^[1-9]\d*$/, message: '请输入正整数', trigger: 'blur' }],
            minRows: 0,
            hide: true,
            labelWidth: 188,
            display: false
          },
          switchOptionHelper({
            label: '状态',
            width: 110,
            prop: FIELD.STATUS,
            value: true,
            hide: false,
            dicData: [
              { label: '禁用', value: '0' },
              { label: '启用', value: '1' }
            ]
          }),
          textareaOptionHelper({ label: '备注', prop: FIELD.REMAKR, hide: true }),
          { label: '技能证件', prop: FIELD.ATTACHMENT, hide: true, formslot: true }
        ]
      }),
      // 详情-操作记录
      operationRecordCrudOption: crudInModalOptionHelper({
        addBtn: false,
        menu: false,
        column: [
          { label: '操作人', prop: FIELD.OPERAROR, width: 100 },
          { label: '操作时间', prop: FIELD.OPERATION_TIME, width: 137 },
          { label: '操作内容', prop: FIELD.OPERATION }
        ]
      }),
      // 批量配置人员-人员信息-数据
      batchConfigPersonInfoData: [],
      // 批量配置人员-人员信息-avue配置
      personInfoCrudOption: crudInModalOptionHelper({
        addBtn: false,
        viewBtn: false,
        column: [
          {
            label: '用户名称',
            prop: FIELD.USER_NAME,
            type: 'select'
          },
          {
            label: '用户编码',
            prop: FIELD.USER_CODE,
            type: 'select'
          },
          {
            label: '账号名',
            prop: FIELD.ACCOUNT_NAME,
            type: 'select'
          },
          {
            label: '所属部门',
            prop: FIELD.DEPARTMENT,
            type: 'select'
          }
        ]
      })
    };
  },

  mounted() {
    this.$nextTick(() => {
      //搜索与表格结构分隔
      this.$structuralSplit();
    });

    // 获取部门树形数据
    // let tenantId = JSON.parse(localStorage.getItem('saber-tenantId') || '{}').content;
    // this.initData(tenantId);
  },
  methods: {
    // 新增-保存
    handleSavePersonSkillsConfigs() {
      if (this.crudModalState == 'add' || this.crudModalState == 'edit') {
        this.$refs.personInfoForm.validate((valid, done) => {
          if (valid) {
            // 校验技能信息
            if (this.crudSkillData.length == 0) {
              this.$message.error('请添加技能信息');
            } else {
              let params = {
                skills: this.crudSkillData,
                users: [{ isFirst: this.crudModalState == 'add', ...this.personInfoForm }]
              };
              add(params).then(
                () => {
                  this.onLoad(this.page);
                  this.$message({
                    type: 'success',
                    message: '操作成功!'
                  });
                  this.onLoad(this.page);
                  this.handleCrudModalClose();
                },
                (error) => {
                  loading();
                  window.console.log(error);
                }
              );
            }
          }
        });
      } else {
        // 批量配置
        // 校验技能信息
        if (this.batchConfigPersonInfoData.length == 0) {
          this.$message.error('请添加人员信息');
          return;
        }
        if (this.crudSkillData.length == 0) {
          this.$message.error('请添加技能信息');
          return;
        }
        let params = {
          skills: this.crudSkillData,
          users: this.batchConfigPersonInfoData
        };
        add(params).then(
          () => {
            this.onLoad(this.page);
            this.$message({
              type: 'success',
              message: '操作成功!'
            });
            this.onLoad(this.page);
            this.handleCrudModalClose();
          },
          (error) => {
            loading();
            window.console.log(error);
          }
        );
      }
    },
    // 新增-取消
    handleCrudModalClose() {
      this.crudModalVisiable = false;
      this.crudSkillData = [];
      this.operationRecordData = [];
      this.batchConfigPersonInfoData = [];
      this.$refs.personInfoForm.resetFields();
    },
    handleAddSkills() {
      this.addSkillsModalVisible = true;
      this.personSkillForm[FIELD.STATUS] = '1';
    },
    // 新增-配置技能-关闭
    handleAddSkillsModalClose() {
      // 数据清空
      this.addSkillsModalVisible = false;
      this.$refs.personSkillForm.resetFields();
      this.personSkillForm.skillExpirationAlertTime = undefined; // 由于有显示隐藏切换，隐藏时会导致resetFields无法清除
      this.personSkillForm._validaity = [];
      this.fileList = [];
    },
    // 新增-添加技能-确定
    handleAddSkillsComfirm() {
      // 校验
      this.$refs.personSkillForm.validate((valid, done) => {
        if (valid) {
          let validaity = this._get(this.personSkillForm, '_validaity', ['', '']);
          let attachJson = JSON.stringify(this.fileList);
          this.fileList = [];
          this.crudSkillData.push({
            [FIELD.SKILL_ID]: this._get(this.personSkillForm, FIELD.SKILL_ID, ''),
            [FIELD.SKILL_TYPE]: this._get(this.personSkillForm, FIELD.SKILL_TYPE, ''),
            [FIELD.SKILL_NAME]: this._get(this.personSkillForm, FIELD.SKILL_NAME, ''),
            [FIELD.SKILL_CODE]: this._get(this.personSkillForm, FIELD.SKILL_CODE, ''),
            [FIELD.SKILL_LEVEL]: this._get(this.personSkillForm, FIELD.SKILL_LEVEL, ''),
            _validaity: validaity,
            [FIELD.VALIDAITY_START]: this.$moment(validaity[0]).format('YYYY-MM-DD') + ' 00:00:00',
            [FIELD.VALIDAITY_END]: this.$moment(validaity[1]).format('YYYY-MM-DD') + ' 23:59:59',
            [FIELD.warning]: this._get(this.personSkillForm, FIELD.warning, ''),
            [FIELD.STATUS]: this._get(this.personSkillForm, FIELD.STATUS, ''),
            [FIELD.REMAKR]: this._get(this.personSkillForm, FIELD.REMAKR, ''),
            [FIELD.ATTACHMENT]: attachJson
          });
          this.handleAddSkillsModalClose();
          done();
        }
      });
    },

    handleBatchPersonConfigModalClose() {
      this.batchPersonConfigVisible = false;
    },
    handleBatchPersonConfigModalSubmit(selection) {
      // 转换
      const selectedUserID = this.batchConfigPersonInfoData.map((item) => {
        return item[FIELD.USER_ID];
      });
      selection = selection
        .map((item) => {
          return {
            [FIELD.USER_ID]: this._get(item, USER_FIELD.USER_ID, ''),
            [FIELD.USER_NAME]: this._get(item, USER_FIELD.USER_NAME, ''),
            [FIELD.USER_CODE]: this._get(item, USER_FIELD.USER_CODE, ''),
            [FIELD.DEPARTMENT]: this._get(item, USER_FIELD.DEPARTMENT, ''),
            [FIELD.ACCOUNT_NAME]: this._get(item, USER_FIELD.ACCOUNT_NAME, ''),
            isFirst: true
          };
        })
        .filter((item) => {
          return !selectedUserID.includes(item[FIELD.USER_ID]);
        });
      this.batchConfigPersonInfoData = [...this.batchConfigPersonInfoData, ...selection];
      this.handleBatchPersonConfigModalClose();
    },

    configSkillFormRowDel(row) {
      this.crudSkillData = this.crudSkillData.filter((item) => {
        return item !== row;
      });
    },
    // initData(tenantId) {
    //   getDeptTree(tenantId).then((res) => {
    //     const column = this.findObject(this.option.column, 'deptId');
    //     column.dicData = res.data.data;
    //   });
    // },

    /**表格操作 START */
    rowUpdate(row, index, done, loading) {
      update(row).then(
        () => {
          this.onLoad(this.page);
          this.$message({
            type: 'success',
            message: '操作成功!'
          });
          done();
        },
        (error) => {
          loading();
          console.log(error);
        }
      );
    },
    rowSave(row, done, loading) {
      // 没添加技能不能保存
      add(row).then(
        () => {
          this.onLoad(this.page);
          this.$message({
            type: 'success',
            message: '操作成功!'
          });
          done();
        },
        (error) => {
          loading();
          window.console.log(error);
        }
      );
    },
    rowDel(row) {
      this.$confirm('确定将选择数据删除?', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          return remove(row.id);
        })
        .then(() => {
          this.onLoad(this.page);
          this.$message({
            type: 'success',
            message: '操作成功!'
          });
        });
    },
    searchChange(params, done) {
      if (params.deptId) {
        params.deptName = params.deptId;
        delete params.deptId;
      }
      this.query = params;
      this.page.currentPage = 1;
      this.onLoad(this.page, params);
      done();
    },
    searchReset() {
      this.query = {};
      this.onLoad(this.page);
    },
    selectionChange(list) {
      this.selectionList = list;
    },
    currentChange(currentPage) {
      this.page.currentPage = currentPage;
    },
    sizeChange(pageSize) {
      this.page.pageSize = pageSize;
    },
    refreshChange() {
      this.onLoad(this.page, this.query);
    },
    onLoad(page, params = {}) {
      this.loading = true;
      getList(page.currentPage, page.pageSize, Object.assign(params, this.query)).then((res) => {
        const data = res.data.data;
        this.page.total = data.total;
        this.data = data.records;
        this.loading = false;
        this.selectionClear();
      });
    },
    selectionClear() {
      this.selectionList = [];
      this.$refs.crud.toggleSelection();
    },
    openCrudModal(type) {
      this.crudModalState = type; // type = 'add', 'edit', 'view'
      this.crudModalVisiable = true;
    },
    handleAdd() {
      this.personInfoFormOption.detail = false;
      this.openCrudModal('add');
      this.crudSkillData = [];
      this.operationRecordData = [];
    },
    handleView(rowData) {
      this.personInfoFormOption.detail = true;
      this.openCrudModal('view');
      this.personInfoForm[FIELD.USER_ID] = this._get(rowData, FIELD.USER_ID, '');
      this.personInfoForm[FIELD.USER_NAME] = this._get(rowData, FIELD.USER_NAME, '');
      this.personInfoForm[FIELD.USER_CODE] = this._get(rowData, FIELD.USER_CODE, '');
      this.personInfoForm[FIELD.DEPARTMENT] = this._get(rowData, FIELD.DEPARTMENT, '');
      this.personInfoForm[FIELD.ACCOUNT_NAME] = this._get(rowData, FIELD.ACCOUNT_NAME, '');
      getDetail(rowData[FIELD.USER_ID]).then(({ data }) => {
        let skillList = data.data.skillVOList;
        skillList.forEach((_data) => {
          _data._validaity = [_data[FIELD.VALIDAITY_START], _data[FIELD.VALIDAITY_END]];
        });
        this.crudSkillData = skillList;
      });
      let user_name = this._get(rowData, FIELD.USER_NAME, '');
      getOperationLog(user_name).then(({ data }) => {
        this.operationRecordData = data.data.records;
      });
    },
    handleEdit(rowData) {
      this.personInfoFormOption.detail = true;
      this.openCrudModal('edit');
      this.personInfoForm[FIELD.USER_ID] = this._get(rowData, FIELD.USER_ID, '');
      this.personInfoForm[FIELD.USER_NAME] = this._get(rowData, FIELD.USER_NAME, '');
      this.personInfoForm[FIELD.USER_CODE] = this._get(rowData, FIELD.USER_CODE, '');
      this.personInfoForm[FIELD.DEPARTMENT] = this._get(rowData, FIELD.DEPARTMENT, '');
      this.personInfoForm[FIELD.ACCOUNT_NAME] = this._get(rowData, FIELD.ACCOUNT_NAME, '');
      getDetail(rowData[FIELD.USER_ID]).then(({ data }) => {
        this.crudSkillData = data.data.skillVOList;
      });
    },
    handleDelete(row) {
      this.$confirm('确定将选择数据删除?', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          return remove(row.userId).then(() => {
            this.onLoad(this.page);
          });
        })
        .then(() => {
          this.onLoad(this.page);
          this.$message({
            type: 'success',
            message: '操作成功!'
          });
        });
    },
    /**表格操作 END*/

    handleBatchConfig() {
      this.openCrudModal('batchConfig');
    },
    // 批量配置
    // batchConfigpersonSkills() {},

    codeClose(value, data) {
      this.onLoad(this.page);
    },

    beforeOpen(done, type) {
      this.defaults.principleName.type = ['view'].includes(type) ? 'input' : 'search';
      if (['edit', 'view'].includes(type)) {
        getDetail(this.form.id).then((res) => {
          this.form = res.data.data || this.form;
        });
      }
      done();
    },
    handleSkillFormBeforeOpen(done, type) {
      let attachJson = this.skillForm.attachJson || '[]';
      this.fileList = JSON.parse(attachJson);
      done();
    },
    handleSkillFormBeforeClose(done, type) {
      this.fileList = [];
      done();
    },
    // 回写数据到表单
    getSelectedRows(rowData) {
      switch (this.modalName) {
        case 'UserList':
          this.personInfoForm[FIELD.USER_ID] = this._get(rowData, USER_FIELD.USER_ID, '');
          this.personInfoForm[FIELD.USER_NAME] = this._get(rowData, USER_FIELD.USER_NAME, '');
          this.personInfoForm[FIELD.USER_CODE] = this._get(rowData, USER_FIELD.USER_CODE, '');
          this.personInfoForm[FIELD.DEPARTMENT] = this._get(rowData, USER_FIELD.DEPARTMENT, '');
          this.personInfoForm[FIELD.ACCOUNT_NAME] = this._get(rowData, USER_FIELD.ACCOUNT_NAME, '');
          break;
        case 'skillList':
          this.isGKJNYXQ = rowData.isValidPeriod;
          this.personSkillForm[FIELD.SKILL_NAME] = this._get(rowData, SKILL_FIELD.SKILL_NAME, '');
          this.personSkillForm[FIELD.SKILL_TYPE] = this._get(rowData, SKILL_FIELD.SKILL_TYPE, '');
          this.personSkillForm[FIELD.SKILL_CODE] = this._get(rowData, SKILL_FIELD.SKILL_CODE, '');
          this.personSkillForm[FIELD.SKILL_LEVEL] = this._get(rowData, SKILL_FIELD.SKILL_LEVEL, '');
          this.personSkillForm[FIELD.SKILL_ID] = this._get(rowData, SKILL_FIELD.SKILL_ID, '');
          break;
        // case 'batchConfigUserList':
        //   this.batchConfigPersonInfoData.push({
        //     [FIELD.USER_ID]: this._get(rowData, USER_FIELD.USER_ID, ''),
        //     [FIELD.USER_NAME]: this._get(rowData, USER_FIELD.USER_NAME, ''),
        //     [FIELD.USER_CODE]: this._get(rowData, USER_FIELD.USER_CODE, ''),
        //     [FIELD.DEPARTMENT]: this._get(rowData, USER_FIELD.DEPARTMENT, ''),
        //     [FIELD.ACCOUNT_NAME]: this._get(rowData, USER_FIELD.ACCOUNT_NAME, ''),
        //     isFirst: true
        //   });
        //   break;
        default:
          break;
      }
    },
    // 重新加载公用表格弹窗组件
    newKey() {
      this.timer = new Date().getTime();
    },
    openSkillListModal(modalName = 'skillList') {
      this.$refs.commonModalTemplate.showModal();
      this.modalName = modalName;
      this.tableOption = {
        modalTitle: '技能列表（双击进行选择）',
        url: API_URLS.SKILL_LIST,
        query: { status: 1 }, // 只查询启用状态的技能
        isPage: true,
        rowSelectionType: 'single',
        columnDefs: [
          {
            label: '技能类型',
            type: 'select',
            prop: SKILL_FIELD.SKILL_TYPE,
            dicUrl: API_URLS.SKILL_TYPE,
            props: {
              label: 'dictValue',
              value: 'dictKey'
            }
          },
          inputOptionHelper({ label: '技能名称', prop: SKILL_FIELD.SKILL_NAME }),
          inputOptionHelper({ label: '技能编码', prop: SKILL_FIELD.SKILL_CODE }),
          {
            label: '技能等级',
            type: 'select',
            prop: SKILL_FIELD.SKILL_LEVEL,
            dicUrl: API_URLS.SKILL_LEVEL,
            props: {
              label: 'dictValue',
              value: 'dictKey'
            }
          }
        ]
      };
    },
    //
    openUserListModal(modalName = 'UserList') {
      if (this.crudModalState == 'batchConfig') {
        this.batchPersonConfigVisible = true;
        return;
      }
      this.$refs.commonModalTemplate.showModal();
      this.modalName = modalName;
      this.tableOption = {
        modalTitle: '人员配置（双击进行选择）',
        url: API_URLS.PERSON_CONFIG,
        isPage: true,
        rowSelectionType: 'single',
        columnDefs: [
          inputOptionHelper({ label: '用户名称', prop: USER_FIELD.USER_NAME }),
          { label: '用户编码', prop: USER_FIELD.USER_CODE },
          { label: '账号名', prop: USER_FIELD.ACCOUNT_NAME },
          { label: '所属部门', prop: USER_FIELD.DEPARTMENT }
        ]
      };
    },
    personInfoRowDel(row) {
      this.batchConfigPersonInfoData = this.batchConfigPersonInfoData.filter((item, index) => {
        return item != row;
      });
    },
    // 文件上传
    handleBeforeUpload(file) {
      return this.validateFileType(file);
    },
    handleUploadSuccess(res) {
      this.fileList.push({
        attachmentId: res.data.attachId,
        link: res.data.link,
        name: res.data.originalName
      });
    },
    removeFile(file) {
      this._forEach(this.fileList, (item, index) => {
        if (item.attachmentId === file.attachmentId) {
          this.fileList.splice(index, 1);
        }
      });
    },
    getFileType(url) {
      // 从URL中提取文件名
      const filename = url.split('/').pop();
      // 提取文件名的扩展名
      const fileExtension = filename.split('.').pop();
      return fileExtension;
    },
    validateFileType(file) {
      const acceptFileTypes = ['png', 'gif', 'bmp', 'jpeg', 'jpg', 'doc', 'docx', 'xlsx', 'xls', 'pdf'];
      const isSuitFileType = acceptFileTypes.includes(this.getFileType(file.name));
      if (!isSuitFileType) {
        this.$message({
          message: '上传文件只能是图片或者word、excel、pdf格式',
          type: 'warning',
          duration: 2000
        });
      }
      const isLt10MB = file.size / 1024 / 1024 < 10;
      if (!isLt10MB) {
        this.$message.error('上传文件大小不能超过 10MB');
      }
      return isSuitFileType && isLt10MB;
    },
    isImageFile(filename) {
      let ext = filename.split('.').pop().toLowerCase();
      return ['jpg', 'jpeg', 'png', 'gif', 'bmp'].includes(ext);
    }
  }
};
</script>

<style lang="scss">
.person-skills-modal .el-dialog {
  .el-dialog__body {
    padding: 30px 20px;
    padding-top: 0px;
    max-height: 650px;
    overflow: scroll;
  }
}
</style>
